<template>
  <div class="home">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="deployment-card">
          <template #header>
            <div class="card-header">
              <span>项目部署</span>
              <el-button type="primary" @click="createNewDeployment">
                <el-icon><Plus /></el-icon>
                新建部署
              </el-button>
            </div>
          </template>
          
          <div class="deployment-list">
            <el-empty v-if="deployments.length === 0" description="暂无部署记录" />
            <div v-else class="deployment-items">
              <div
                v-for="deployment in deployments"
                :key="deployment.id"
                class="deployment-item"
              >
                <div class="deployment-info">
                  <h3>{{ deployment.projectName }}</h3>
                  <p class="repo-url">{{ deployment.repoUrl }}</p>
                  <p class="deploy-path">部署路径: {{ deployment.deployPath }}</p>
                  <p v-if="deployment.currentDeployPath" class="local-path">
                    当前部署: {{ deployment.currentDeployPath }}
                  </p>
                  <p v-if="deployment.deployHistory && deployment.deployHistory.length > 0" class="deploy-count">
                    部署次数: {{ deployment.deployHistory.length }}
                  </p>
                </div>
                <div class="deployment-status">
                  <el-tag :type="getStatusType(deployment.status)">
                    {{ getStatusText(deployment.status) }}
                  </el-tag>
                  <p class="deploy-time">{{ formatTime(deployment.updatedAt) }}</p>
                </div>
                <div class="deployment-actions">
                  <el-button
                    type="primary"
                    size="small"
                    :loading="deployment.status === 'deploying'"
                    @click="deployProject(deployment)"
                  >
                    重新部署
                  </el-button>
                  <el-button
                    type="warning"
                    size="small"
                    @click="editDeployment(deployment)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="info"
                    size="small"
                    @click="viewProjectLogs(deployment)"
                  >
                    日志
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteDeployment(deployment.id)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="stats-card">
          <template #header>
            <span>部署统计</span>
          </template>
          
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-number">{{ stats.total }}</div>
              <div class="stat-label">总部署数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number success">{{ stats.success }}</div>
              <div class="stat-label">成功部署</div>
            </div>
            <div class="stat-item">
              <div class="stat-number failed">{{ stats.failed }}</div>
              <div class="stat-label">失败部署</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="log-card" style="margin-top: 20px;">
          <template #header>
            <span>最近日志</span>
          </template>
          
          <div class="log-content">
            <div
              v-for="log in recentLogs"
              :key="log.id"
              class="log-item"
            >
              <div class="log-time">{{ formatTime(log.timestamp) }}</div>
              <div class="log-message">{{ log.message }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 部署表单对话框 -->
    <el-dialog
      v-model="showDeployForm"
      :title="editingDeployment ? '编辑部署' : '新建部署'"
      width="600px"
      :close-on-click-modal="false"
    >
      <DeployForm 
        :deployment="editingDeployment"
        :is-edit="!!editingDeployment"
        @close="closeDeployForm" 
        @success="onDeploySuccess" 
      />
    </el-dialog>

    <!-- 项目日志对话框 -->
    <el-dialog
      v-model="showProjectLogs"
      :title="viewingDeployment ? `${viewingDeployment.projectName} - 部署日志` : '项目日志'"
      width="800px"
      :close-on-click-modal="false"
    >
      <ProjectLogs 
        v-if="viewingDeployment"
        :deployment="viewingDeployment"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import DeployForm from '@/components/DeployForm.vue'
import ProjectLogs from '@/components/ProjectLogs.vue'
import { useDeploymentStore } from '@/stores/deployment'

const deploymentStore = useDeploymentStore()
const showDeployForm = ref(false)
const editingDeployment = ref<any>(null)
const showProjectLogs = ref(false)
const viewingDeployment = ref<any>(null)

const deployments = ref<any[]>([])
const stats = ref({
  total: 0,
  success: 0,
  failed: 0
})
const recentLogs = ref<any[]>([])

onMounted(async () => {
  await loadData()
})

const loadData = async () => {
  try {
    const [deploymentsData, statsData, logsData] = await Promise.all([
      deploymentStore.getDeployments(),
      deploymentStore.getStats(),
      deploymentStore.getLogs()
    ])
    
    deployments.value = deploymentsData
    stats.value = statsData
    recentLogs.value = logsData
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    success: 'success',
    failed: 'danger',
    deploying: 'warning',
    pending: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    success: '部署成功',
    failed: '部署失败',
    deploying: '部署中',
    pending: '等待中'
  }
  return statusMap[status] || '未知状态'
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString('zh-CN')
}

const deployProject = async (deployment: any) => {
  try {
    await deploymentStore.deployProject(deployment.id)
    ElMessage.success('部署任务已启动')
    await loadData()
  } catch (error) {
    ElMessage.error('启动部署失败')
  }
}

const deleteDeployment = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个部署配置吗？', '确认删除', {
      type: 'warning'
    })
    
    await deploymentStore.deleteDeployment(id)
    ElMessage.success('删除成功')
    await loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const createNewDeployment = () => {
  editingDeployment.value = null
  showDeployForm.value = true
}

const editDeployment = (deployment: any) => {
  console.log('编辑部署:', deployment)
  editingDeployment.value = deployment
  showDeployForm.value = true
}

const viewProjectLogs = (deployment: any) => {
  viewingDeployment.value = deployment
  showProjectLogs.value = true
}

const closeDeployForm = () => {
  showDeployForm.value = false
  editingDeployment.value = null
}

const onDeploySuccess = async () => {
  showDeployForm.value = false
  editingDeployment.value = null
  await loadData()
}
</script>

<style scoped>
.home {
  max-width: 1200px;
  margin: 0 auto;
}

.deployment-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.deployment-list {
  min-height: 200px;
}

.deployment-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.deployment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: white;
}

.deployment-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.repo-url {
  color: #606266;
  font-size: 14px;
  margin: 4px 0;
}

.deploy-path {
  color: #909399;
  font-size: 12px;
  margin: 4px 0;
}

.local-path {
  color: #67c23a;
  font-size: 12px;
  margin: 4px 0;
  font-weight: 500;
}

.deploy-count {
  color: #909399;
  font-size: 12px;
  margin: 4px 0;
}

.deployment-status {
  text-align: center;
}

.deploy-time {
  font-size: 12px;
  color: #909399;
  margin: 8px 0 0 0;
}

.deployment-actions {
  display: flex;
  gap: 8px;
}

.stats-content {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-item {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.failed {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 8px;
}

.log-content {
  max-height: 300px;
  overflow-y: auto;
}

.log-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  font-size: 12px;
  color: #909399;
}

.log-message {
  font-size: 14px;
  color: #303133;
  margin-top: 4px;
}
</style>
